package com.zhitong.money.services;

import com.zhitong.money.entity.TokenEntity;
import com.zhitong.money.mapper.ITokenEntityMapper;
import com.zhitong.money.services.api.ITokenEntityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * @Author: Andy Zhang
 * @Description:
 * @Date: 11:25 2021/3/12
 * @Company: wisecard
 */
@Service
public class TokenService implements ITokenEntityService {

    //12小时后过期
    private final static int EXPIRE = 3600 * 12;

    @Autowired
    private ITokenEntityMapper tokenEntityMapper;

    @Override
    public TokenEntity findByToken(String token){
        TokenEntity byToken = tokenEntityMapper.findByToken(token);
        return byToken;
    }

    @Override
    public TokenEntity createToken(String tid) {

        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

        TokenEntity byUid = tokenEntityMapper.findByTid(tid);
        if (byUid==null){
            byUid=new TokenEntity();
            byUid.setToken(UUID.randomUUID().toString().replaceAll("-",""));
            byUid.setTid(tid);
            byUid.setUpdateTime(now);
            byUid.setExpireTime(expireTime);
            tokenEntityMapper.add(byUid);
        }else{
            byUid.setToken(UUID.randomUUID().toString().replaceAll("-",""));
            byUid.setExpireTime(expireTime);
            byUid.setUpdateTime(now);
            tokenEntityMapper.update(byUid);
        }
        return byUid;
    }

    @Override
    public void logout(String token)   {
        TokenEntity byToken = tokenEntityMapper.findByToken(token);
        token=UUID.randomUUID().toString().replaceAll("-","");
        TokenEntity tokenEntity=new TokenEntity();
        tokenEntity.setToken(token);
        tokenEntity.setTid(byToken.getTid());
        tokenEntityMapper.del(byToken.getTid());
        tokenEntityMapper.add(tokenEntity);
    }

}
